import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

import router from '@/router'


// create an axios instance
// 基地址与响应世间
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://ihrm-java.itheima.net', 
  baseURL:  process.env.VUE_APP_BASE_API,
  timeout: 5000
})


// 拦截器
// request interceptor
// 请求拦截
service.interceptors.request.use(
  config => {
    console.log("请求拦截",config,store)
    const token = store.state.user.token
    if(token){
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)



// 响应拦截
// response interceptor
service.interceptors.response.use(

  response => {
    if(response.data.success === false){
      // 错误信息
      return Promise.reject(new Error(response.data.message))
    }else{
      // 返回数据
      return response.data
    }
  },
  error => {
    console.dir(error) 
    if(error.response.data.code === 10002){
      store.dispatch('user/logout')
      router.push('/login?rteurn=' + router.currentRoute.path)
    }
    
  }
)


export default service


